package cn.swing.his.affair.webapi.controller;

import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import cn.swing.his.affair.service.IAffairService;
import cn.swing.his.common.web.JsonPage;
import cn.swing.his.common.web.JsonResult;
import cn.swing.his.pojo.affair.dto.MedicalEquipmentDetailsDTO;
import cn.swing.his.pojo.affair.dto.MedicineDetailsDTO;
import cn.swing.his.pojo.affair.vo.*;
import cn.swing.his.pojo.user.vo.DoctorDetailsVO;
import cn.swing.his.user.service.IUserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping(value = "/affair", produces = "application/json;charset=utf-8")
@Api(tags = "事务模块")
@Slf4j
public class AffairController {
    @Autowired
    private IAffairService affairService;

    @DubboReference
    private IUserService userService;

    // ===================增
    // 插入药品信息
    @ApiOperation("插入药品信息")
    @PostMapping("/insertMedicineDetails")
    public JsonResult<Integer> insertMedicineDetails(MedicineDetailsDTO medicineDetails) {
        Integer result = affairService.insertMedicineDetails(medicineDetails);
        return JsonResult.ok("插入成功", result);
    }

    // 插入设备信息
    @ApiOperation("插入设备信息")
    @PostMapping("/insertMedicalEquipmentDetails")
    public JsonResult<Integer> insertMedicalEquipmentDetails(MedicalEquipmentDetailsDTO medicalEquipmentDetails) {
        Integer result = affairService.insertMedicalEquipmentDetails(medicalEquipmentDetails);
        return JsonResult.ok("插入成功", result);
    }

    @ApiOperation("新增某时刻的排班信息")
    @PostMapping("/insertScheduleInfo")
    public JsonResult<Integer> insertScheduleInfo(Integer timeId, Integer dayId, Integer doctorId, Integer roomId) {
        Integer result = affairService.insertScheduleInfo(timeId, dayId, doctorId, roomId);
        return JsonResult.ok("新增成功", result);
    }

    // ===================删
    // 删除药品信息
    @ApiOperation("删除药品信息")
    @PostMapping("/deleteMedicineDetails")
    public JsonResult<Integer> deleteMedicineDetails(Integer id) {
        Integer result = affairService.deleteMedicineDetailsById(id);
        return JsonResult.ok("删除成功", result);
    }

    // 删除设备信息
    @ApiOperation("删除设备信息")
    @PostMapping("/deleteMedicalEquipmentDetails")
    public JsonResult<Integer> deleteMedicalEquipmentDetails(Integer id) {
        Integer result = affairService.deleteMedicalEquipmentById(id);
        return JsonResult.ok("删除成功", result);
    }

    // 删除某一时刻的排班信息
    @ApiOperation("删除某一时刻的排班信息")
    @PostMapping("/deleteScheduleInfoByTimeAndDayAndRoom")
    public JsonResult<Integer> deleteScheduleInfoByTimeAndDayAndRoom(Integer timeId, Integer dayId, Integer roomId) {
        Integer result = affairService.deleteScheduleInfoByTimeAndDayAndRoom(timeId, dayId, roomId);
        return JsonResult.ok("删除成功", result);
    }

    // ===================改
    // 更新药品信息
    @ApiOperation("更新药品信息")
    @PostMapping("/updateMedicineDetails")
    public JsonResult<Integer> updateMedicineDetails(MedicineDetailsDTO medicineDetails) {
        Integer result = affairService.updateMedicineDetails(medicineDetails);
        return JsonResult.ok("更新成功", result);
    }

    // 更新设备信息
    @ApiOperation("更新设备信息")
    @PostMapping("/updateMedicalEquipmentDetails")
    public JsonResult<Integer> updateMedicalEquipmentDetails(MedicalEquipmentDetailsDTO medicalEquipmentDetails) {
        Integer result = affairService.updateMedicalEquipmentDetails(medicalEquipmentDetails);
        return JsonResult.ok("修改成功", result);
    }

    // ===================查
    // 查询药品列表
    @ApiOperation("查询药品列表")
    @PostMapping("/medicineList")
    public JsonPage<MedicineDetailsVO> getMedicineList(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<MedicineDetailsVO> list = affairService.getMedicineList();
        return JsonPage.restPage(new PageInfo<>(list));
    }

    // 根据关键字查询药品信息
    @ApiOperation("根据关键字查询药品信息")
    @PostMapping("/getMedicineInfoByKeyword")
    public JsonPage<MedicineDetailsVO> getMedicineByKeyword(Integer pageNum, Integer pageSize, String keyword) {
        PageHelper.startPage(pageNum, pageSize);
        List<MedicineDetailsVO> list = affairService.getMedicineByKeyword(keyword);
        return JsonPage.restPage(new PageInfo<>(list));
    }

    // 获取设备列表
    @ApiOperation("获取设备列表")
    @PostMapping("/medicalEquipmentList")
    public JsonPage<MedicalEquipmentDetailsVO> getMedicalEquipmentList(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<MedicalEquipmentDetailsVO> list = affairService.getMedicalEquipmentList();
        return JsonPage.restPage(new PageInfo<>(list));
    }

    // 获取设备列表
    @ApiOperation("根据关键字查询设备信息")
    @PostMapping("/getMedicalEquipmentListByKeyword")
    public JsonPage<MedicalEquipmentDetailsVO> getMedicalEquipmentListByKeyword(Integer pageNum, Integer pageSize, String keyword) {
        PageHelper.startPage(pageNum, pageSize);
        List<MedicalEquipmentDetailsVO> list = affairService.getMedicalEquipmentListByKeyword(keyword);
        return JsonPage.restPage(new PageInfo<>(list));
    }

    // 获取设备信息
    @ApiOperation("获取时间段")
    @PostMapping("/getScheduleList")
    public JsonResult<List<ScheduleVO>> getScheduleList() {
        List<ScheduleVO> list = affairService.getScheduleList();
        return JsonResult.ok("获取成功", list);
    }

    @ApiOperation("根据部门ID获取该部门的医生")
    @PostMapping("/getDoctorSimple")
    public JsonResult<List<DoctorSimpleVO>> getDoctorSimpleByRoomId(Integer roomId) {
        List<DoctorSimpleVO> list = affairService.getDoctorSimpleByRoomId(roomId);
        return JsonResult.ok("获取成功", list);
    }

    @ApiOperation("获取某一时刻的排班人员ID")
    @PostMapping("/getSchedule")
    public JsonResult<List<Integer>> getScheduleByTimeAndDayAndRoom(Integer timeId, Integer dayId, Integer roomId) {
        List<Integer> list = affairService.getScheduleByTimeAndDayAndRoom(timeId, dayId, roomId);
        return JsonResult.ok("获取成功", list);
    }

    @ApiOperation("获取某一时刻的排班人员姓名")
    @PostMapping("/getScheduleName")
    public JsonResult<List<String>> getScheduleUserName(Integer timeId, Integer dayId, Integer roomId) {
        List<String> list = affairService.getScheduleUserName(timeId, dayId, roomId);
        return JsonResult.ok("获取成功", list);
    }

    @ApiOperation("获取科室列表")
    @PostMapping("/getRooms")
    public JsonResult<List<RoomSimpleVO>> getRooms() {
        List<RoomSimpleVO> list = affairService.getRooms();
        return JsonResult.ok("获取成功", list);
    }

    @ApiOperation("获取排班状况")
    @PostMapping("/getScheduleStatus")
    public JsonResult<Integer> getScheduleStatus(Integer timeId, Integer dayId, Integer doctorId) {
        Integer result = affairService.getScheduleStatus(timeId, dayId, doctorId);
        return JsonResult.ok("获取成功", result);
    }

//    @ApiOperation("获取本人信息")
//    @PostMapping("")
//    public JsonResult<DoctorDetailsVO> getUserInfo(Integer doctorId) {
//
//    }

    /**
     * 导出接口
     */
    @ApiOperation(value = "导出药物信息")
    @GetMapping("/exportMedicineDetails")
    public void exportMedicineDetails(HttpServletResponse response) throws Exception {
        // 从数据库查询出所有的数据
        List<MedicineDetailsVO> list = affairService.getMedicineList();
        log.debug("list：{}", list);

        // 通过工具类创建writer 写出到磁盘路径
//        ExcelWriter writer = ExcelUtil.getWriter(filesUploadPath + "/用户信息.xlsx");
        // 在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //自定义标题别名
        writer.addHeaderAlias("id", "id");
        writer.addHeaderAlias("type", "药品类型");
        writer.addHeaderAlias("name", "药品名称");
        writer.addHeaderAlias("manufacturer", "生产厂家");
        writer.addHeaderAlias("purchasePrice", "进价（￥）");
        writer.addHeaderAlias("salePrice", "售价（￥）");
        writer.addHeaderAlias("batchNumber", "产品批号");
        writer.addHeaderAlias("description", "描述");
        writer.addHeaderAlias("stock", "库存");
        writer.addHeaderAlias("position", "存放位置");
        writer.addHeaderAlias("productionTime", "生产日期");
        writer.addHeaderAlias("expirationTime", "失效日期");
        writer.addHeaderAlias("gmtCreated", "创建时间");
        writer.addHeaderAlias("gmtModified", "修改时间");
        // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(list, true);
        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("药品信息 " + LocalDateTime.now(), "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();
    }

    /**
     * 导出接口
     */
    @ApiOperation(value = "导出设备信息")
    @GetMapping("/exportMedicalEquipmentDetails")
    public void exportMedicalEquipmentDetails(HttpServletResponse response) throws Exception {
        // 从数据库查询出所有的数据
        List<MedicalEquipmentDetailsVO> list = affairService.getMedicalEquipmentList();
        log.debug("list：{}", list);

        // 通过工具类创建writer 写出到磁盘路径
//        ExcelWriter writer = ExcelUtil.getWriter(filesUploadPath + "/用户信息.xlsx");
        // 在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //自定义标题别名
        writer.addHeaderAlias("id", "id");
        writer.addHeaderAlias("type", "药品类型");
        writer.addHeaderAlias("name", "药品名称");
        writer.addHeaderAlias("roomId", "管理科室");
        writer.addHeaderAlias("manufacturer", "生产厂家");
        writer.addHeaderAlias("purchasePrice", "进价（￥）");
        writer.addHeaderAlias("batchNumber", "产品批号");
        writer.addHeaderAlias("description", "描述");
        writer.addHeaderAlias("stock", "库存");
        writer.addHeaderAlias("position", "存放位置");
        writer.addHeaderAlias("productionTime", "生产日期");
        writer.addHeaderAlias("maintenancePersonnel", "上次维护人员");
        writer.addHeaderAlias("details", "维护信息");
        writer.addHeaderAlias("gmtCreated", "创建时间");
        writer.addHeaderAlias("gmtModified", "修改时间");
        // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(list, true);
        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("设备信息 " + LocalDateTime.now(), "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();
    }

}
